<template>
  <el-page-header>
    <template #breadcrumb>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item >
          <router-link to="/manager/mangerindex" class="menu-router">首页</router-link>
        </el-breadcrumb-item>
        <el-breadcrumb-item
        ><router-link to="/manager/usermanager" class="menu-router">用户管理</router-link></el-breadcrumb-item
        >
      </el-breadcrumb>
    </template>
    <template #content>

      <span class="text-large font-600 mr-3"> 用户管理 </span>
    </template>
  </el-page-header>
  <el-table :data="tableData" style="width: 100%" >
    <el-table-column
        prop="imageUrl"
        label="头像"
        width="180">
      <template #default="{ row }">
        <el-image
            v-if="row.imageurl"
            :src="row.imageurl"
            fit="cover"
            style="width: 50%; height: 50%;">
          <div slot="error" class="image-slot">
            图片加载失败
          </div>
        </el-image>
      </template>
    </el-table-column>
    <el-table-column fixed prop="username" label="账号" width="150" />
    <el-table-column prop="email" label="邮箱" width="120" />
    <el-table-column prop="age" label="年龄" width="120" />
    <el-table-column prop="phone" label="电话" width="120" />
    <el-table-column prop="banned" label="账户状态" width="120">
      <template #default="{ row }">
        <span :style="{ color:row.color}">{{ row.banned }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="amount" label="余额" width="600"  />

    <el-table-column fixed="right" label="操作" width="120" >
      <template #default="{row}">
        <el-button link type="primary" size="small" class="el-button1" @click="showupdateusernamepassworddiglog(row.username)">修改密码</el-button>
        <el-button link type="primary" size="small" @click="showuserdetailfunc(row.id)">修改个人信息</el-button>
        <el-button link type="primary" size="small" @click="getroleByusername(row.username,row.id)">赋予角色</el-button>
        <el-button link type="primary" size="small" @click="banneduser(row.id)">{{row.buttonspan}}</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog
      v-model="centerDialogVisible"
      title="重置密码"
      width="500"
      align-center
  >
    <div>
      <span>请输入新密码:   </span>
      <el-input
          v-model="input"
          style="width: 240px"
          type="password"
          placeholder="请输入重置密码"
          show-password
      />

    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">Cancel</el-button>
        <el-button @click="updateusernamepassword(usernames,input)">重置</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
      v-model="showuserdetail"
      title="修改用户信息"
      width="500"
      align-center
  >
    <div>
      <span class="diglog-span">更新头像: </span>
      <el-upload
          class="avatar-uploader"
          action="http://localhost:8090/food/updateuserimageurl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </div>
    <div>
      <span class="diglog-span">更新用户名: </span>
      <el-input
          v-model="username"
          style="width: 240px"
          type="text"
          placeholder="请输入用户名"
      />
    </div>
    <div>
      <span class="diglog-span">更新邮箱: </span>
      <el-input
          v-model="email"
          style="width: 240px"
          type="text"
          placeholder="请输入邮箱"
      />
    </div>
    <div>
      <span class="diglog-span">更新年龄: </span>
      <el-input
          v-model="age"
          style="width: 240px"
          type="text"
          placeholder="请输入年龄"
      />
    </div>
      <div>
        <span class="diglog-span">更新电话: </span>
        <el-input
            v-model="phone"
            style="width: 240px"
            type="text"
            placeholder="请输入电话"
        />
      </div>


    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">Cancel</el-button>
        <el-button @click="updateuserdetail(id,username,email,phone,age,imageUrls)">修改</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
      v-model="showrole"
      title="赋予角色"
      width="500"
      align-center
  >
    <div v-for="(role,index) in roles" :key=index>
      <el-checkbox v-model="role.checked" :label="role.roleName" border :disabled="role.disabled"></el-checkbox>

    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">Cancel</el-button>
        <el-button @click="insertroleByroleId(roles)">赋予</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from "vue";
import {
  getallroleservice,
  getalluserservice, getroleBytheusernameservice, insertroleByRoleIdService,
  updateuserdetailservice,
  updateusernamepasswordservice, updateuserstatesservice
} from "../api/food.js";
import {ElMessage, ElNotification} from "element-plus";
import { h } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import {a} from "vite/dist/node/types.d-aGj9QkWt";
const tableData=reactive([])
const imageUrl = ref('')
const imageUrls=ref()
const showrole=ref(false)
const input=ref();
const theuserrole=reactive([])
const username=ref('')
const usernames=ref()
const userids=ref()
const email=ref('')
const phone=ref('')
const age=ref()
const buttonspan=ref('')
const roles=reactive([])
const roleid=reactive([])
const id=ref(0)
const showuserdetail=ref(false)
const centerDialogVisible=ref(false)
const getalluser = async () => {
  const response = await getalluserservice()
  if (response.code === 200) {
    tableData.splice(0, tableData.length); // 清空原有数据
    response.date.forEach(item => {
      if(item.banned===0){
        item.buttonspan='封禁用户'
        item.banned="正常"
        item.color="green"
      }else if(item.banned===1){
        item.buttonspan='解封用户'
        item.banned="封禁"
        item.color="red"
      }
      tableData.push(item)
    })

  }else {
    console.log("获取用户信息失败")
  }
  console.log(response)

}
onMounted(()=>{
  getalluser();
  getallrole();
})

const showupdateusernamepassworddiglog = async (username) => {
  centerDialogVisible.value=true;
  usernames.value=username;
}
const showuserdetailfunc = async (userid) => {
  showuserdetail.value=true;
  id.value=userid;

}
const updateusernamepassword = async (usernames,input) => {
  const response = await updateusernamepasswordservice(usernames,input)
  if (response.code === 200) {
    centerDialogVisible.value=false;
    await getalluser();
    ElNotification({
      title: '提示',
      message: h('i', { style: 'color: teal' }, '修改密码成功'),
    })
  }else {
    console.log("修改密码失败")
  }
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  imageUrls.value = response.date;
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
const updateuserdetail = async (id,username,email,phone,age,imageUrl) => {
  const response = await updateuserdetailservice(id,username,email,phone,age,imageUrl)
  if (response.code === 200) {
    showuserdetail.value=false;
    await getalluser();
    ElNotification({
      title: '提示',
      message: h('i', { style: 'color: teal' }, '修改用户信息成功'),
    })
  }else {
    console.log("修改用户信息失败")
  }
}
const getallrole = async () => {
  const response=await getallroleservice()
  if (response.code === 200) {
    roles.splice(0, roles.length); // 清空原有数据
    response.date.forEach(item => {
      item.checked=false;
      item.disabled=false;
      roles.push(item)
    })
  }else {
    console.log("获取角色信息失败")
  }

}
const getroleByusername = async (username,userid) => {
  showrole.value=true;
  console.log("userid="+userid)
  id.value=userid;
  console.log("id="+id.value)
  const response=await getroleBytheusernameservice(username)
  if (response.code === 200) {
    theuserrole.splice(0, theuserrole.length); // 清空原有数据
    response.date.forEach(item => {
      theuserrole.push(item)
    })
   await showselectrole(roles,theuserrole);

  }else {
    console.log("获取角色信息失败")
  }

}
const showselectrole = (roles,theuserrole) => {
  roles.forEach(role => {
    role.checked=false;
    role.disabled=false;
    theuserrole.forEach(roles=>{
      if (role.roleName===roles.roleName){
        role.checked=true;
        role.disabled=true;
      }
    })
  })
}
const insertroleByroleId = async (roles) => {
  roleid.splice( 0, roleid.length)
  roles.forEach(role=>{
    if (role.checked){
      roleid.push(role.id)
    }
    console.log(roleid)
  })
  const reponse=await insertroleByRoleIdService(roleid,id.value)
  if (reponse.code === 200) {
    showrole.value=false;
    await getalluser();
    ElNotification({
      title: '提示',
      message: h('i', { style: 'color: teal' }, '赋予角色成功'),
    })
  }else {
    console.log("赋予角色失败")
  }
}
const banneduser = async (id) => {
  const response= await  updateuserstatesservice(id)
  if (response.code === 200) {
    await getalluser();
    ElNotification({
      title: '提示',
      message: h('i', { style: 'color: teal' }, '封禁成功'),
    })
  }else {
    console.log("封禁失败")
  }
}
</script>

<style scoped>
.el-button1{
  margin-left: 10px;
}
.el-table-amount{
  text-align: center;
  color: #ff0000;
  font-weight: bold;
  font-size: 20px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.diglog-span{
  margin-right: 10px;
  font-size: 20px;
  font-weight: bold;
  color: rosybrown;
  margin-bottom: 10px;
  margin-top: 10px;
  display: inline-block;
}
.el-status{
  margin-left: 10px;
  font-size: 20px;
  font-weight: bold;



}
</style>